/*
 * TCPSocket.cpp
 *
 *  Created on: 21/06/2014
 *      Author: Vitor
 */

#include "TCPSocket.h"

TCPSocket::TCPSocket() {
}

TCPSocket::TCPSocket(const char* hostname, short port) {
	if (SDLNet_ResolveHost(&ip_address, hostname, port) < 0) {
		fprintf(stderr, "SDLNet_ResolveHost(%s, %hu): %s.\n", hostname, port,
				SDLNet_GetError());
		exit(1);
	}
}

TCPSocket::TCPSocket(TCPsocket socket) :
		socket(socket), ip_address(*SDLNet_TCP_GetPeerAddress(socket)) {
}

TCPSocket::~TCPSocket() {
}

void TCPSocket::open() {
	if (!(socket = SDLNet_TCP_Open(&ip_address))) {
		fprintf(stderr, "SDLNet_TCP_Open(%x): %s.\n", ip_address.host,
				SDLNet_GetError());
		exit(1);
	}
}

void TCPSocket::close() {
	SDLNet_TCP_Close(socket);
}

bool TCPSocket::accept(TCPSocket& incoming_connection) {
	TCPsocket client_socket;
	if ((client_socket = SDLNet_TCP_Accept(socket))) {
		incoming_connection = TCPSocket(client_socket);
		return true;
	}
	return false;
}

void TCPSocket::send(const std::vector<char>& bytes) {
	if (SDLNet_TCP_Send(socket, &bytes[0], bytes.size()) < (int) bytes.size()) {
		fprintf(stderr, "SDLNet_TCP_Send: %s\n", SDLNet_GetError());
		exit(1);
	}
}

bool TCPSocket::recv(int size, std::vector<char>& bytes) {
	bytes.resize(size);
	if (SDLNet_TCP_Recv(socket, &bytes[0], size) <= 0) {
		return false;
	}
	return true;
}
